package util.req;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.*;

/**
 * 请求工具类
 *
 * @author shane
 * @version 1.0.0
 * @Date 2020/12/23 16:08
 */
public class RequestUtil {

    /**
     * 获取请求参数
     *
     * @param request
     * @return
     */
    public static Map<String, String> getRequestParams(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();

        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        return params;
    }

    /**
     * 参数排序
     *
     * @param params 请求参数
     * @return
     * @throws Exception
     */
    public static String sortParams(Map<String, Object> params) throws Exception {
        return sortParams(params, 1, true);
    }

    /**
     * 参数排序
     *
     * @param params 请求参数
     * @param sort   排序，大于0正序，小余0倒叙
     * @param encode 是否编码
     * @return
     * @throws Exception
     */
    public static String sortParams(Map<String, Object> params, Integer sort, Boolean encode) throws Exception {
        StringBuffer buff = new StringBuffer();
        if (params != null) {
            Set<String> keySets = params.keySet();
            List<String> keys = new ArrayList<String>(keySets);

            if (sort > 0) {
                Collections.sort(keys);
            } else if (sort < 0) {
                Collections.reverse(keys);
            }

            for (String key : keys) {
                buff.append(key).append("=").append(params.get(key)).append("&");
            }
        }

        String str = "";
        if (buff.length() > 0) {
            str = buff.substring(0, buff.length() - 1);
        }

        if (encode) {
            str = URLEncoder.encode(str, "utf-8");
        }

        return str;
    }
}
